package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     *
     * 新增菜品,同时保存对应口味数据
     * @param dishDto
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        //菜品id
        Long dishId=dishDto.getId();

        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map((item) ->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }


    /**
     *
     *修改数据和菜品的关联数据
     * @param dishDto
     */
    @Transactional
    public void updateDishWithFlavor(DishDto dishDto) {
        //操作dish表,执行update sql
        this.updateById(dishDto);
        //2.操作dish_flavor,先删除原来的菜品关联的所有口味数据 delete from dish_flavor where dish_id=?
        LambdaQueryWrapper <DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //3.重新插入最想口味数据inset
        List<DishFlavor>flavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor : flavors) {
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }

    /**
     *
     * 删除菜品
     * @param ids
     */
    @Transactional
    public void deleteDishWithFlavor( List<Long> ids) {
        this.removeByIds(ids);

        ids.stream().map((item)->{
            LambdaQueryWrapper<DishFlavor>queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(item!=null,DishFlavor::getDishId,item );
            dishFlavorService.remove(queryWrapper);

            return null;

        }).collect(Collectors.toList());





    }
}
